<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<GeneCMS.Models.View.BoardViewModel>" %>

<%@ Import Namespace="BulletOnRails4NET.Controllers" %>
<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
    Web Pages Manager
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">

    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js"></script>

    <script type="text/javascript" src="<%= PathResolver.GetSiteRoot() + "Scripts/ListLogic.js" %>"></script>

    <script type="text/javascript" src="<%= PathResolver.GetSiteRoot() + "Scripts/jquery.form.js" %>"></script>

    <script type="text/javascript">
        
        
function create_hierarhy_list(top_level, children_by_parent, to_string_func, get_id_func,
lookup_data) {

            html = "<ol>";
            for (var top_level_item in top_level)
            {
                html += create_hierarhy_entry(top_level[top_level_item], children_by_parent,
                 to_string_func, get_id_func, lookup_data);
            }
            html += "</ol>";
            return html;
}
function create_hierarhy_entry(item, children_by_parent, to_string_func, get_id_func,
lookup_data) {

    html = "<li>";
    lookup_idx = lookup_data.length;
    lookup_data[lookup_idx] = item;
    html += to_string_func(item, lookup_idx);
    item_children = children_by_parent[get_id_func(item)];
    if (item_children != null)
    {
        html += "<ol>";
        for (child_idx in children_by_parent[get_id_func(item)]) //had to use original hash look up b/c js was reusing var space when using recursion and making item_children undefined for the calling function
        {
            children = children_by_parent[get_id_func(item)][child_idx];
            html += create_hierarhy_entry(children, children_by_parent,
            to_string_func, get_id_func, lookup_data);
        }
        html += "</ol>";
    }
    html += "</li>";
    return html;
}

function get_page_id(page)
{
    return page.ID;
}

function edit_contents(lookup_idx) {
    page = _all_pages[lookup_idx];
    $.post("render", "page_id=" + page.ID,
                    function(data) {
                        //reload_pages_list();
                    }
                  );
}

function page_to_string(page, lookup_idx)
{
    html = page.Title +
    '&nbsp<a href="#" onclick="show_edit(' + lookup_idx + ', _edit_fields_model)">Edit</a>' +
    '&nbsp<a href="#" onclick="add_child_page(' + lookup_idx + ', _edit_fields_model)">Add Child Page</a>' +
    '&nbsp<a href="#" onclick="delete_page(' + lookup_idx + ')">Delete</a>' +
    '&nbsp<a href="<%= PathResolver.GetSiteRoot() %>website/editpage/' + page.ID + '">Edit Contents</a>' +
    '&nbsp<a href="<%= PathResolver.GetSiteRoot() %>contents/list/' + page.ID + '">Edit Contents (Safe mode)</a>' +
    '<div id="edit_form_' + page.ID + '"></div>';
    if (page.Folder != null && page.Folder.length > 0) {
        html += "<br/><strong>" + page.Folder + " Folder</strong>"
    }
    return html;
}



function reload_pages_list()
{
    $.getJSON("<%= PathResolver.GetSiteRoot() %>website/GetPages", null, function (data) {
    html_list = create_hierarhy_list(data.TopLevelPages, data.ChildPages, page_to_string, get_page_id, _all_pages);
        $("#pages_list").html(html_list);
            });
}

function add_child_page(lookup_idx, edit_fields_model) {
    show_form(lookup_idx);
    //Set the parent ID of the new record
    page = _all_pages[lookup_idx];
    $("#ID_field").attr("disabled", true);
    $("#ParentPageID_field").val(page == null ? "" : page.ID);
    $("#ParentPageID_field").attr("disabled", true);
    $("#save_form_btn").click(function(e) {
        // stop normal submit click
        e.preventDefault();
        save_changes("<%= PathResolver.GetSiteRoot() %>Pages/Create");
    });
}

function delete_page(lookup_idx) {
    var result = confirm("Are you sure you want to delete this page? ALL of it child pages will be deleted.")
    if (result == true) {

        page = _all_pages[lookup_idx];
        $.post("<%= PathResolver.GetSiteRoot() %>pages/delete", "ids_to_delete="+ page.ID,
                    function(data) {
                        reload_pages_list();
                    }
                  );
    }
}

function show_edit(lookup_idx, edit_fields_model) {
    show_form(lookup_idx);
    //Show item to be edited
    show_item_in_form(lookup_idx, edit_fields_model);
    $("#ID_field").attr("disabled", true);
    //Add the callback again b/c save_form_btn got recreated in show_item_in_form
    $("#save_form_btn").click(function(e) {
        // stop normal submit click
    e.preventDefault();
    save_changes("<%= PathResolver.GetSiteRoot() %>Pages/Edit/" + page.ID);
    });
}

function show_form(lookup_idx) {
    //Clear older edit form if any
    if (_curr_edit_form_div_id != null)
        $("#" + _curr_edit_form_div_id).empty();

    //Draw the form in the current record
    page = _all_pages[lookup_idx];
    if (page == null) {
        _curr_edit_form_div_id = "edit_form_root";
        $("#edit_form_root").html(_edit_form_html);
    }
    else {
        _curr_edit_form_div_id = "edit_form_" + page.ID;
        $("#edit_form_" + page.ID).html(_edit_form_html);
    }
}

//Sends via Ajax POST the contents of the details_form
function save_changes(post_url) {
    page = _all_pages[_curr_selected_record_id];
    var queryString = $('#details_form').formSerialize();
    $.post(post_url, queryString,
                    function(data) {
                        handle_response_from_crud(data, page);
                    }
                  );
                    return false;
                }

function handle_response_from_crud(response_json, page) {

    $(".input-validation-error").removeClass("input-validation-error");
    $("#error_messages").empty();
    // response_json = eval("(" + response_json + ")" );
    if (response_json.toString().substring(0, 30).toUpperCase().indexOf("<HTML") >= 0) {
        //the response is a html to display
        $("#error_messages").html(response_json);
    }
    else {
        if (response_json.type == "Error") {
            //Display the error message in each field
            violations = response_json.violations;
            err_html = "<p>The following errors ocurred:</p><ul>";
            for (var violation_idx = 0; violation_idx < violations.length;
    violation_idx++) {
                err_html += "<li>" +
        violations[violation_idx].ErrorMessage + "</li>";
                $("#" + violations[violation_idx].PropertyName
        + "_field").addClass("input-validation-error");
            }
            $("#error_messages").html(err_html + "</ul>");
        }
        else {
            reload_pages_list();
        }
    }
};

var _curr_selected_record_id = -1;
function show_item_in_form(lookup_idx, edit_fields_model) {
    _curr_selected_record_id = lookup_idx;
    var row_data = _all_pages[lookup_idx];
    for (var col_idx = 0; col_idx < edit_fields_model.length; col_idx++) {
        col_value = row_data[edit_fields_model[col_idx].index]; //Note we are chg this (not the same as listlogic's
        col_field_id = edit_fields_model[col_idx].index + "_field";
        $("#" + col_field_id).val(col_value);
    }
}

var _edit_fields_model, _edit_form_html, _all_pages, _curr_edit_form_div_id, _response_html;
$(document).ready(function() {
    _curr_edit_form_div_id = null;
    _all_pages = [];
    //Create the form
    _edit_fields_model = [{ "name": "ID", "width": 21, "index": "ID" },
    { "name": "Title", "width": 90, "index": "Title" },
    { "name": "Folder", "width": 63, "index": "Folder" },
    { "name": "InMenu", "width": 63, "index": "InMenu" },
    { "name": "Keywords", "width": 63, "index": "Keywords" },
    { "name": "Description", "width": 63, "index": "Description" },
    { "name": "CustomHeadContent", "width": 100, "index": "CustomHeadContent" },
    { "name": "Position", "width": 63, "index": "Position" },
     { "name": "Parent Page ID", "width": 105, "index": "ParentPageID" },
{ "name": "Url", "width": 90, "index": "Url"}];
    _edit_form_html = '<form id="details_form" action="" onsubmit="return false;" method="post">'+
    '<div class="validation-summary-errors" id="error_messages">'+
    '</div>';
    _edit_form_html += generate_edit_form(_edit_fields_model, [], []);
    _edit_form_html += '<button id="save_form_btn" name="SaveForm">Save</button></form>';
    reload_pages_list();
});

        
    </script>

    <h2>
        Web Pages Manager</h2>
        <p><a href="#" onclick="add_child_page(-1, _edit_fields_model)">Add Page to root</a></p>
        <div id="edit_form_root"></div>
    <div id="pages_list">
    </div>
    <p>Click on the link below to export your website to your production web server: <br />
    <%= Html.ActionLink("Publish Website", "PublishWebsite") %></p>
	<h2>Website's Menu Settings</h2>
	<% Html.RenderPartial("MenuEdit", Model.Menu); %>
	<% Html.RenderPartial("WebsiteSettings", Model.Website); %>

</asp:Content>
